import React, { useState, useRef, useEffect } from 'react';
import { Button, Space, message, Popconfirm, Tag, Tooltip, Modal, Select, Form, Input } from 'antd';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, ReloadOutlined, UserOutlined } from '@ant-design/icons';

import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { UserList, RemoveUsersFromGroupRequest, AssignGroupRequest, UserProfile } from '@/services/generated/src/index';

const { Option } = Select;

interface GroupUserManagementProps {
  groupId: number;
  groupName: string;
  onUserCountChange?: (count: number) => void;
}

const GroupUserManagement: React.FC<GroupUserManagementProps> = ({
  groupId,
  groupName,
  onUserCountChange
}) => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);

  // 添加用户Modal相关状态
  const [addUserModalVisible, setAddUserModalVisible] = useState(false);
  const [availableUsers, setAvailableUsers] = useState<UserProfile[]>([]);
  const [addUserForm] = Form.useForm();

  // 批量移除用户
  const handleBatchRemove = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要移除的用户');
      return;
    }

    try {
      setLoading(true);
      await autoLoginInDev();

      const request: RemoveUsersFromGroupRequest = {
        user_ids: selectedRowKeys.map(key => Number(key))
      };

      await apiClients.permissions.permissionsGroupsRemoveUsersCreate({
        id: groupId,
        removeUsersFromGroupRequest: request
      });

      message.success(`成功移除${selectedRowKeys.length}个用户`);
      setSelectedRowKeys([]);
      actionRef.current?.reload();
    } catch (error) {
      message.error('批量移除用户失败');
    } finally {
      setLoading(false);
    }
  };

  // 移除单个用户
  const handleRemoveUser = async (userId: number, username: string) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      const request: RemoveUsersFromGroupRequest = {
        user_ids: [userId]
      };

      await apiClients.permissions.permissionsGroupsRemoveUsersCreate({
        id: groupId,
        removeUsersFromGroupRequest: request
      });

      message.success(`成功移除用户 ${username}`);
      actionRef.current?.reload();
    } catch (error) {
      message.error(`移除用户 ${username} 失败`);
    } finally {
      setLoading(false);
    }
  };

  // 加载可用用户（不在当前组中的用户）
  const loadAvailableUsers = async () => {
    try {
      await autoLoginInDev();

      const response = await apiClients.users.usersList({ pageSize: 1000 });
      const responseData = (response as any).data || response;
      const allUsers = responseData?.items || [];

      // 获取当前组的用户
      const groupUsersResponse = await apiClients.permissions.permissionsGroupsUsersRetrieve({
        id: groupId,
        pageSize: 1000
      });
      const groupUsersData = (groupUsersResponse as any).data || groupUsersResponse;
      const groupUsers = groupUsersData?.items || [];
      const groupUserIds = new Set(groupUsers.map((user: any) => user.id));

      // 过滤出不在组中的用户
      const availableUsersList = allUsers.filter((user: any) => !groupUserIds.has(user.id));
      setAvailableUsers(availableUsersList);
    } catch (error) {
      message.error('加载可用用户失败');
    }
  };

  // 添加用户到组
  const handleAddUsers = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      const request: AssignGroupRequest = {
        user_ids: values.user_ids,
        expires_at: values.expires_at?.toISOString(),
        notes: values.notes || ''
      };

      await apiClients.permissions.permissionsGroupsAssignUsersCreate({
        id: groupId,
        assignGroupRequest: request
      });

      message.success(`成功添加${values.user_ids.length}个用户到组`);
      setAddUserModalVisible(false);
      addUserForm.resetFields();
      actionRef.current?.reload();
    } catch (error) {
      message.error('添加用户失败');
    } finally {
      setLoading(false);
    }
  };

  // 打开添加用户Modal
  const handleOpenAddUserModal = () => {
    loadAvailableUsers();
    setAddUserModalVisible(true);
  };

  // 表格列定义
  const columns: ProColumns<UserList>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      copyable: true,
    },
    {
      title: '姓名',
      dataIndex: 'full_name',
      width: 120,
      search: false,
      render: (_, record) => {
        // 手动构建全名显示
        if (record.last_name && record.first_name) {
          return `${record.last_name}${record.first_name}`;
        } else if (record.first_name) {
          return record.first_name;
        } else if (record.last_name) {
          return record.last_name;
        }
        return record.username;
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 200,
      copyable: true,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 100,
      search: false,
      render: (_, record) => (
        <Tag color={record.is_active ? 'green' : 'red'}>
          {record.is_active ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '角色',
      dataIndex: 'is_staff',
      width: 100,
      search: false,
      render: (_, record) => {
        if (record.is_superuser) {
          return <Tag color="red">超级管理员</Tag>;
        } else if (record.is_staff) {
          return <Tag color="blue">管理员</Tag>;
        } else {
          return <Tag>普通用户</Tag>;
        }
      },
    },
    {
      title: '最后登录',
      dataIndex: 'last_login',
      width: 160,
      search: false,
      render: (_, record) => {
        if (record.last_login) {
          return new Date(record.last_login).toLocaleString();
        }
        return '从未登录';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      render: (_, record) => [
        <Popconfirm
          key="remove"
          title={`确定要从组"${groupName}"中移除用户"${record.username}"吗？`}
          onConfirm={() => handleRemoveUser(record.id, record.username)}
        >
          <Button
            type="link"
            size="small"
            danger
            loading={loading}
            icon={<DeleteOutlined />}
          >
            移除
          </Button>
        </Popconfirm>
      ],
    },
  ];

  return (
    <div>
      <p style={{ marginBottom: 16, color: '#666' }}>
        管理组"{groupName}"内的用户，支持搜索、过滤和批量操作
      </p>
      
      <ProTable<UserList>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          try {
            await autoLoginInDev();

            const response = await apiClients.permissions.permissionsGroupsUsersRetrieve({
              id: groupId,
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.username || params.email,
              isActive: params.is_active,
              isStaff: params.is_staff,
            });

            console.log('🚀 组用户列表API响应:', response);

            // 🔑 关键：手动提取data字段
            const responseData = (response as any).data || response;
            const items = responseData?.items || [];
            const total = responseData?.total || 0;

            // 通知父组件用户数量变化
            if (onUserCountChange) {
              onUserCountChange(total);
            }

            return {
              data: items,
              success: true,
              total: total,
            };
          } catch (error) {
            message.error('获取组用户列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle={`组内用户列表`}
        toolBarRender={() => [
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleOpenAddUserModal}
          >
            添加用户
          </Button>,
        ]}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选择 <strong>{selectedRowKeys.length}</strong> 个用户
              <Button type="link" size="small" onClick={onCleanSelected}>
                取消选择
              </Button>
            </span>
          </Space>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => (
          <Space size={16}>
            <Popconfirm
              title={`确定要从组中移除选中的${selectedRowKeys.length}个用户吗？`}
              onConfirm={handleBatchRemove}
            >
              <Button
                type="link"
                size="small"
                danger
                loading={loading}
                icon={<DeleteOutlined />}
              >
                批量移除
              </Button>
            </Popconfirm>
          </Space>
        )}
        size="small"
      />

      {/* 添加用户Modal */}
      <Modal
        title={`添加用户到组"${groupName}"`}
        open={addUserModalVisible}
        onCancel={() => {
          setAddUserModalVisible(false);
          addUserForm.resetFields();
        }}
        onOk={() => addUserForm.submit()}
        destroyOnClose
        width={600}
      >
        <Form
          form={addUserForm}
          layout="vertical"
          onFinish={handleAddUsers}
        >
          <Form.Item
            name="user_ids"
            label="选择用户"
            rules={[{ required: true, message: '请选择要添加的用户' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择要添加到组的用户"
              showSearch
              filterOption={(input, option) =>
                (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
              }
              style={{ width: '100%' }}
            >
              {availableUsers.map(user => (
                <Option key={user.id} value={user.id}>
                  {user.username} ({user.full_name || user.email})
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="notes"
            label="备注"
            help="可选，添加用户到组的备注信息"
          >
            <Input.TextArea
              placeholder="请输入备注信息（可选）"
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default GroupUserManagement;
